package com.gnerv.sylvanas.framework.common.tools;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64Tools {

    private Base64Tools() {}

    public static String encode(String data) {
        return encode(data.getBytes(StandardCharsets.UTF_8));
    }

    public static String encode(byte[] data) {
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(data);
    }

    public static String decode(String data) {
        return decode(data.getBytes(StandardCharsets.UTF_8));
    }

    public static String decode(byte[] data) {
        byte[] decodedBytes = Base64.getDecoder().decode(data);
        return new String(decodedBytes);
    }

    public static String encodeUrl(String data) {
        return encodeUrl(data.getBytes(StandardCharsets.UTF_8));
    }

    public static String encodeUrl(byte[] data) {
        Base64.Encoder encoder = Base64.getUrlEncoder();
        return encoder.encodeToString(data);
    }

    public static String decodeUrl(String data) {
        return decodeUrl(data.getBytes(StandardCharsets.UTF_8));
    }

    public static String decodeUrl(byte[] data) {
        byte[] decodedBytes = Base64.getUrlDecoder().decode(data);
        return new String(decodedBytes);
    }

    // 图片转Base64
    public String encodeImage(String path) throws IOException {
        byte[] fileContent = Files.readAllBytes(Paths.get(path));
        return Base64.getEncoder().encodeToString(fileContent);
    }

    // Base64转图片
    public void decodeImage(String data, String path) throws IOException {
        byte[] decodedBytes = Base64.getDecoder().decode(data);
        Files.write(Paths.get(path), decodedBytes);
    }

    // 创建Basic Auth头
    public String encodeAuth(String username, String password) {
        String auth = username + ":" + password;
        return "Basic " + Base64.getEncoder().encodeToString(auth.getBytes());
    }

    // 解析Basic Auth头
    public String[] decodeAuth(String authHeader) {
        String encoded = authHeader.substring("Basic ".length());
        String decoded = new String(Base64.getDecoder().decode(encoded));
        return decoded.split(":");
    }

}
